import Food from './Food';
import Panel from './Panel'
import Snake from './Snake'

class GameControl {
    food: Food;
    panel: Panel;
    snake: Snake;
    direction: string = '';
    timer: any;

    constructor () {
        this.food = new Food();
        this.panel = new Panel(2);
        this.snake = new Snake();
    }

    start() {
        document.documentElement.addEventListener('keydown', this.keyDown.bind(this))
    }

    keyDown(event: KeyboardEvent) {
        const verify: string[] = ['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight'];
        const key = event.key;
        if (['ArrowDown', 'ArrowUp'].includes(this.direction) && ['ArrowDown', 'ArrowUp'].includes(key)) return;    
        if (['ArrowLeft', 'ArrowRight'].includes(this.direction) && ['ArrowLeft', 'ArrowRight'].includes(key)) return;    
        if (verify.includes(key)) {
            this.direction = key;
            this.run();
        }
        // 暂停游戏
        if (key === ' ') {
            this.stop();
        }
    }

    run () {
        if (this.timer) clearTimeout(this.timer)
        let x = this.snake.x;
        let y = this.snake.y;


        switch (this.direction) {
            case 'ArrowDown':
                y += 10
                break;
            case 'ArrowUp':
                y -= 10
                break;
            case 'ArrowLeft':
                x -= 10
                break;
            case 'ArrowRight':
                x += 10
                break;
        }
        // 禁止反向操作

        // 检测超出边界
        let mtxBoundary:boolean = x >= 300 || x < 0;
        let mtyBoundary:boolean = y >= 300 || y < 0;
        if (mtxBoundary || mtyBoundary) {
            this.stop()
            console.log('麻瓜🐍已超出边界')
            return;
        }
        // 吃到食物
        if (x === this.food.x && y === this.food.y) {
            console.log('吃到食物了')
            this.panel.addScore();
            this.food.changePosition();
            this.snake.addBody()
        }

        if (this.snake.x !== x) {
            this.snake.x = x;
        }
        if (this.snake.y !== y) {
            this.snake.y = y;
        }


        this.timer = setTimeout(this.run.bind(this), 300 - (this.panel.level - 1) * 30 || 30)
    }

    stop() {
        if (this.timer) {
            clearTimeout(this.timer)
        }
    }
}

export default GameControl;